// pages/shopping/shopping.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    num: 0, // 商品数量
    buyCount: 0, //勾选的商品数量
    isDelete: false, //是否删除商品
    select: [], //选中商品的cartId
    allCount: 0, //商品总价格
    allCheck: false, //商品全选
    shoppingList: [] //购物车商品列表
  },

  /**
   * 取消删除商品
   */
  cancelDelete: function() {
    this.setData({
      isDelete: !this.data.isDelete
    })
  },

  /**
   * 进入商品详情
   */
  goCommodityDetail: function(e) {
    let productId = e.currentTarget.dataset.productid
    wx.navigateTo({
      url: '../commodityDetail/commodityDetail?productId=' + productId,
    })
  },
  /**
   * 确认下单
   */
  confirmOrder: function() {
    let that = this;
    if (this.data.buyCount != 0) {
      let str = '您选中了' + ' ' + that.data.buyCount + ' ' + '件商品';
      wx.showModal({
        content: str,
        cancelText: '再买一点',
        cancelColor: '#999',
        confirmColor: '#05b973',
        success: function(res) {
          if (res.cancel) {} else {
            wx.navigateTo({
              url: '../confirmOrder/confirmOrder?json=' + escape(JSON.stringify(that.data.select)) + '&price=' + that.data.allCount + '&isCart=' + 1,
              success: function() {
                that.setData({ //清空选中商品，商品总价以及商品数量
                  select: [],
                  allCount: 0,
                  buyCount: 0,
                })
              }
            })
          }
        }
      })

    } else {
      wx.showModal({
        content: '您还没有选择宝贝哦',
        confirmColor: '#05b973',
        showCancel: false,
      })
    }

  },
  /**
   * 管理商品
   */
  management: function() {
    this.setData({
      isDelete: !this.data.isDelete
    })
  },
  /**
   * 删除商品
   */
  delete: function() {
    let that = this;
    let str = '确认删除' + ' ' + that.data.buyCount + ' ' + '件商品';
    wx.showModal({
      content: str,
      cancelText: '再想想',
      cancelColor: '#05b973',
      confirmColor: '#999',
      success: function(res) {
        if (res.cancel) {} else {
          let a;
          for (a in that.data.shoppingList) {
            if (that.data.shoppingList[a].check == true) {

              let cartIdList = [];
              cartIdList.push(that.data.shoppingList[a].cartId)
              console.log(that.data.shoppingList[a])
              console.log(cartIdList)
              console.log(" ++++")
              wx.request({
                url: 'https://www.xiaozheng8.com/shop/cart/delete',
                method: 'post',
                data: {
                  cartIdList: cartIdList,
                },
                success: function(res) {
                  that.getshoppingList();
                  app.getshoppingList();
                 console.log(app.globalData.num);
                }
              })
            }
          }

        }

      }
    })
  },
  /**
   * 查找购物车商品列表
   */
  getshoppingList: function() {
    let that = this;

    wx.request({
      url: 'https://www.xiaozheng8.com/shop/cart/findByUserId',
      method: 'post',
      data: {
        userId: wx.getStorageSync("userId"),
      },
      success: function(res) {
        console.log(res)
        let arr = res.data.data.pic;
        that.setData({
          shoppingList: res.data.data,
          num: res.data.data.length,
          allCheck: false
        })
        console.log("zschaxundaode")
        console.log(res.data.data)
        wx.hideLoading()
      }
    })
  },


  /**
   * 是否选中商品事件
   */
  check: function(e) {
    let a = e.currentTarget.dataset.index; //当前点击的商品索引
    if (this.data.shoppingList[a].check == false) {
      this.data.shoppingList[a].check = true;
    } else {
      this.data.shoppingList[a].check = false

    }
    this.setData({
      shoppingList: this.data.shoppingList,
    })
    console.log(this.data.shoppingList)
    let x = 0;
    for (let i = 0; i < this.data.num; i++) {
      if (this.data.shoppingList[i].check == false) {
        this.setData({
          allCheck: false
        })
      } else {
        x++;
        if (x == this.data.num) {
          this.setData({
            allCheck: true
          })
        }
      }
    }
    this.getSelectList(this.data.shoppingList);
    this.getTotalPrice();
  },
  /**
   * 商品全选
   */
  allCheck: function() {
    let allCheck = this.data.allCheck;
    let shoppingList = this.data.shoppingList;
    if (allCheck == true) {
      for (var i in shoppingList) {
        shoppingList[i].check = false;
      };
      this.setData({
        allCheck: false,
        shoppingList: shoppingList,
        select: []
      })
    } else {
      for (var i in shoppingList) {
        shoppingList[i].check = true;
      };
      this.setData({
        allCheck: true,
        shoppingList: shoppingList,
        select: shoppingList
      })
    }
    console.log("全选完的列表")
    console.log(this.data.select)
    this.getTotalPrice();
  },
  /**
   * 商品合计总价
   */
  getTotalPrice: function() {
    let shoppingList = this.data.shoppingList;
    let count = 0;
    let allCount = 0;
    let buyCount = 0;
    for (let i = 0; i < shoppingList.length; i++) { // 循环列表得到每个数据

      if (shoppingList[i].check == true) { // 判断选中才会计算价格
        buyCount++;
        allCount += shoppingList[i].productCount * shoppingList[i].price; // 所有价格加起来
       
       
      }
    }
    // console.log(allCount);
    
    var total=allCount.toFixed(2);
    console.log(total)
    this.setData({
      shoppingList: shoppingList,
      allCount: total,
      buyCount: buyCount
    })
  },

  /**
   * 获取选中商品列表
   */
  getSelectList: function(shoppingList) {
    this.data.select = []; //清空列表
    for (let i = 0; i < this.data.num; i++) {

      if (shoppingList[i].check == true) {
        this.data.select.push(shoppingList[i])
        // console.log(shoppingList[i])
        // console.log("------")
        this.setData({
          select: this.data.select
        })
      }
    }
    // console.log("=======")
    // console.log(this.data.select)
  },

  /**
   * 增加商品数量事件
   */
  add: function(e) {
    let that = this;
    let a = e.currentTarget.dataset.id;
    that.data.shoppingList[a].productCount++;
    wx.request({
      url: 'https://www.xiaozheng8.com/shop/cart/update',
      method: 'post',
      data: {
        userId: wx.getStorageSync("userId"),
        productId: that.data.shoppingList[a].productId,
        productCount: that.data.shoppingList[a].productCount,
      },
      success: function(res) {
        console.log(res)
        that.setData({
          shoppingList: that.data.shoppingList
        })
      },
    })

    console.log('----zl-----')
    console.log(this.data.shoppingList)
    this.getTotalPrice();
  },
  /**
   * 减少商品数据量事件
   */
  less: function(e) {
    let that = this;
    let a = e.currentTarget.dataset.id;
    if (this.data.shoppingList[a].productCount > 1) {
      this.data.shoppingList[a].productCount--;
      wx.request({
        url: 'https://www.xiaozheng8.com/shop/cart/update',
        method: 'post',
        data: {
          userId: wx.getStorageSync("userId"),
          productId: that.data.shoppingList[a].productId,
          productCount: that.data.shoppingList[a].productCount,
        },
        success: function(res) {
          console.log(res)
          that.setData({
            shoppingList: that.data.shoppingList
          })
        },
      })
      this.getTotalPrice();
    } else {
      wx.showModal({
        content: '不能再少了哦',
        showCancel: false,
        confirmColor: '#05b973'
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showLoading({
      title: '加载中',
    });
    this.getshoppingList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getshoppingList();
    app.getshoppingList();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})